<template>
  <div>
      <el-button type="primary" icon="el-icon-plus" @click="showDialog">
        添加
      </el-button>
       <el-table
       :data='list'
       border
      style="width: 100%;margin-top:20px">
      <el-table-column
        align="center"
        type="index"
        label="序号"
        width="80">
      </el-table-column>
      <el-table-column
        align="center"
        prop="tmName"
        label="姓名"
        width="180">
      </el-table-column>
      <el-table-column
        align="center"
        prop="logoUrl"
        label="logo">
        <template slot-scope="{row,$index}"> 
          <!-- <img src="row.logoUrl" alt=""> -->
          {{row}} {{$index}}
        </template> 
      </el-table-column>
        <el-table-column
        align="center"
        prop=""
        label="操作">
        <template  slot-scope="{row,$index}">
          <el-button type="warning" icon="el-icon-edit" size="small" @click="updateTradeMark(row)">修改</el-button>
          <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteTradeMark(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--
      pager-count分页器展示的数字有几个比如  < 1 2 3   ....50 >
    -->
     <el-pagination style="margin-top:20px;text-align:center"
      @size-change="handleSizeChange"
      @current-change="getPageList"
      :current-page="page"
      :page-sizes="[3, 5, 7, 9]"
      :page-size="limit"
      :pager-count="9"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total">
    </el-pagination>
    <el-dialog :title="this.tmForm.id?'修改品牌':'添加品牌'" :visible.sync="dialogFormVisible">
      <el-form style="width:80%" :model="tmForm" :rules="rules" ref="ruleForm">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input  autocomplete="off" v-model="tmForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="图片Logo" label-width="100px" prop="logoUrl">
         <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :show-file-list="false">
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdate">确 定</el-button>
      </div>
  </el-dialog>
  </div>
</template>

<script>
export default {
  name:'TradeMark',
  data() {
          //自定义校验规则
        const validateTmName = (rule, value, callback) => {
          if(value.length<2||value.length>10){
            callback(new Error('品牌2-10位'))
          }else{
            callback()
          }
        }
        return {
          page:1,
          limit:3,
          total:0,
          list:[],
          dialogFormVisible:false,
          //收集品牌的信息  
          tmForm:{
            tmName:'',
            logoUrl:'',
            id:''
          },
          //表单验证规则
          rules:{
            //品牌名称验证规则
            tmName: [
            { required: true, message: '请输入品牌名称', trigger: 'blur' },
             { validator: validateTmName, trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
            ],
            //品牌logo验证规则
            logoUrl: [
              { required: true, message: '请选择图片'}
            ],
          },
        
        }
      },
  computed:{
    
  },
  mounted(){
    this.getPageList()
  },
  methods:{
    //获取列表数据
    async getPageList(pager=1){
      //current-change点击时会触发而且会传参数,参数为当前页数,第一次进页面没有点击默认为一
      this.page = pager
      //解构参数
      const {page,limit} = this;
      const result = await this.$API.trademark.reqTradeMarkList(page,limit)
      console.log(result);
      if(result.code===200){
        this.list = result.data.records
        this.total = result.data.total
      }
    },
    deleteTradeMark(row){
         this.$confirm(`删除${row.tmName}品牌, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const result = await this.$API.trademark.deleteTradeMark(row.id)
          if(result.code==200){
            this.$message({
            type: 'success',
            message: '删除成功!'
            })
            this.getPageList(this.list.length>1?this.page:this.page-1)
          }else{
             this.$message.error('删除失败');
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },

    //改变分页数目
    handleSizeChange(pagesize){
      this.limit = pagesize
      this.getPageList()
    },
    //确定按钮
    async addOrUpdate(){
      //验证字段
      this.$refs.ruleForm.validate(async (resp)=>{
        //如果验证成功
        if(resp){
          //添加或者修改
          this.dialogFormVisible = false
          const  result = await this.$API.trademark.reqAddUpdateTradeMark(this.tmForm);
          if(result.code===200){
            //弹出信息 可能是添加或者修改
            this.$message({
              message:this.tmForm.id?'修改品牌成功':'添加品牌成功',
              type:'success'
            })
            //如果添加停留第一页,如果修改应该留在当前页面
            this.getPageList(this.tmFrom.id?this.page:1)
          }
        }else{
           this.$message.error('格式有误');
           return false;
        }
      })
      

    },
    //点击添加
    showDialog(){
      //清空表单
      this.tmForm ={tmName:'',logoUrl:''}
      this.dialogFormVisible = true
    },
    //修改 row当前用户选中的信息
    updateTradeMark(row){
      this.dialogFormVisible = true 
      //避免修改数组中的值,使用浅拷贝
      this.tmForm = {...row}
    },
    //图片上传成功
     handleAvatarSuccess(res, file) {
      //res file是上传成功之后返回给前端的数据
        this.tmForm.logoUrl = res.data
      },
      //图片上传之前
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }
    }
    
  
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>